"""Used to read fasthenry output file .mat format"""

from scipy import io
from numpy import array
import sys, os, re, cmath

rowpt = re.compile(r"^Row (\d+):\s*(.*)")
freqpt = re.compile(r"^Impedance matrix for frequency =\s*([0-9eE+\-.]+)\s*(\d+)\s*x\s*(\d+)")
dtpt  = re.compile(r"([^j]*?)j")
def read_henry(name):
    fin = open(name, 'r')
    dt = fin.read()
    fin.close()
    lines = dt.splitlines()
    row = []
    mat = []
    for i in range(len(lines)):
        rowname = rowpt.findall(lines[i])
        if rowname:
            row.append(rowname)
            continue
        freqmt = freqpt.findall(lines[i])
        if freqmt:
            mat.append((float(freqmt[0][0]), []))
            for rx in range(int(freqmt[0][2])):
                linedt = [complex((x+'j').replace(" ",'')) for x in dtpt.findall(lines[i+rx+1])]
                linedt = [(x.real, x.imag/2/cmath.pi/float(freqmt[0][0])) for x in linedt]
                mat[-1][1].append(linedt)
    return mat
        
def read2list(mat):
    """data from read_henry() function
Format:
[(freq, [[(R,L),(R,L)],
         [(R,L),(R,L)]]),
(freq, [...]),
...
]
"""
    return ([(item[0], item[1][0][0][0]) for item in mat],  # R11
            [(item[0], item[1][0][0][1]) for item in mat],  # L11
            [(item[0], item[1][1][1][0]) for item in mat],  # R22
            [(item[0], item[1][1][1][1]) for item in mat],  # L22
            [(item[0], item[1][0][1][1]) for item in mat],  # M
            )
k = read_henry('Zcdis_10.00.mat')
print array(read2list(k))

